package com.cxl.bill.server.controller;

import com.cxl.bill.server.bean.ResponseBean;
import com.cxl.bill.server.db.bean.User;
import com.cxl.bill.server.service.UserService;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user")
@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping()
    public String index() {
        return "user api index";
    }

    @PostMapping("/login")
    public ResponseBean<?> login(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password
    ) {
        User dbUser = userService.findByUserName(name);
        if (dbUser!=null){

            if (dbUser.getUserPassword().equals(password)){
                return ResponseBean.ok(dbUser.getId().toString());
            }else {
                return ResponseBean.error("密码错误");
            }
        }else {
            //新增用户
            User newUser = new User();
            newUser.setUserName(name);
            newUser.setUserPassword(password);
            if (userService.insert(newUser)>0){
                return  ResponseBean.ok(userService.findByUserName(name).getId().toString());
            }else {
                return  ResponseBean.error("新增失败");
            }
        }
    }
}
